<template>
	<div class="div-user-sum">
		<div class="div-user-top">
			<span>用户管理</span>
		</div>
		<el-input placeholder="请输入姓名" prefix-icon="el-icon-search" v-model="name" style="width:207px;height:40px;margin-left: 10px" clearable>
		</el-input>
		<el-button type="primary" @click="search" style="margin-left: 5px">搜索</el-button>
		<el-button type="primary" @click="addUserDialog=true" icon="el-icon-circle-plus-outline">添加用户</el-button>
		<el-button type="danger" :disabled="!multipleSelect || multipleSelect.length<=0" @click="removeUsers">批量删除<span v-show='multipleSelect && multipleSelect.length>0'>（{{multipleSelect.length}}）</span></el-button>
		<el-button type="success" @click="dialogImport=true" icon="el-icon-upload2">导入用户</el-button>
		<!--<el-button type="success" @click="exportUser" icon="el-icon-download">导出用户</el-button>-->
		<div style="margin: 10px;">
			<el-table :data="users" border @selection-change="selectionChange">
				<el-table-column type="selection" width="55">
				</el-table-column>
				<el-table-column prop="username" label="用户名" align="center">
				</el-table-column>
				<el-table-column prop="name" label="姓名" align="center">
				</el-table-column>
				<el-table-column prop="deptName" label="所在组织" align="center">
				</el-table-column>
				<el-table-column label="操作" align="center" width='300'>
					<template slot-scope="scope">
						<el-button type="primary" @click="openEdit(scope.row)" size="small">编辑</el-button>
						<el-button type="primary" @click="setPassword(scope.row.userId)" size="small">重置密码</el-button>
						<el-button type="danger" @click="openDelete(scope.row.userId)" size="small">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div style="margin: 10px; text-align: center;">
				<el-pagination background @current-change="currentChange" :current-page="current" :page-size="limit" layout="total,  prev, pager, next, jumper" :total="total">
				</el-pagination>
			</div>
		</div>
		<!-- 添加用户 -->
		<el-dialog title="添加用户" :show-close='false' :close-on-press-escape='false' :close-on-click-modal="false" :visible.sync="addUserDialog" width="720px">
			<el-form :model="addForm" :rules="rules" ref="addForm" :inline="true" style='width: calc(100% - 20px);'>
				<el-row>
					<el-col :span='12'>
						<el-form-item label="用户名" prop="username" label-width="110px">
							<el-input placeholder="请输入用户名" v-model="addForm.username" style="width:207px;" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="真实姓名" prop="name" label-width="110px">
							<el-input placeholder="请输入姓名" v-model="addForm.name" style="width:207px;" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span='12'>
						<el-form-item label="密码" prop="password" label-width="110px">
							<el-input type="password" placeholder="请输入密码" v-model="addForm.password" style="width:207px;" show-password clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="再次输入密码" prop="passwordcheck" label-width="110px">
							<el-input type="password" placeholder="请再次输入密码" v-model="addForm.passwordcheck" style="width:207px;" show-password clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span='12'>
						<el-form-item label="所在组织" prop="deptId" label-width="110px">
							<el-select v-model="addForm.deptId" placeholder="请选择所在组织" style="width:207px;">
								<el-option v-for="item in depts" :key="item.id" :label="item.title" :value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<!--<el-col :span='12'>
						<el-form-item label="角色权限" prop="userRoleList" label-width="110px">
							<el-select v-model="addForm.userRoles" @change='addRoleChange' multiple placeholder="请选择用户角色（可多选）" style="width:207px;">
								<el-option v-for="item in roles" :key="item.roleId" :label="item.roleName" :value="item.roleId"></el-option>
							</el-select>
						</el-form-item>
					</el-col>-->
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetAdd">取 消</el-button>
				<el-button type="primary" @click="addUser" :disabled='dataloading'>确 定</el-button>
			</div>
		</el-dialog>
		<!-- 编辑用户 -->
		<el-dialog title="编辑用户" :show-close='false' :close-on-press-escape='false' :close-on-click-modal="false" :visible.sync="editUserDialog" width="720px">
			<el-form :model="editForm" :rules="rules" ref="editForm" :inline="true" style='width: calc(100% - 20px);'>
				<el-row>
					<el-col :span='12'>
						<el-form-item label="用户名" prop="username" label-width="110px">
							<el-input placeholder="请输入用户名" v-model="editForm.username" style="width:207px;" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label="真实姓名" prop="name" label-width="110px">
							<el-input placeholder="请输入姓名" v-model="editForm.name" style="width:207px;" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span='12'>
						<el-form-item label="所在组织" prop="deptId" label-width="110px">
							<el-select v-model="editForm.deptId" placeholder="请选择所在组织" style="width:207px;">
								<el-option v-for="item in depts" :key="item.id" :label="item.title" :value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<!--<el-col :span='12'>
						<el-form-item label="角色权限" prop="userRoleList" label-width="110px">
							<el-select v-model="editForm.userRoles" @change='editRoleChange' multiple placeholder="请选择用户角色(可多选)" style="width:207px;">
								<el-option v-for="item in roles" :key="item.roleId" :label="item.roleName" :value="item.roleId"></el-option>
							</el-select>
						</el-form-item>
					</el-col>-->
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetEdit">取 消</el-button>
				<el-button type="primary" @click="editUser">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 导入用户 -->
		<el-dialog title="导入用户" :show-close='false' :close-on-press-escape='false' :close-on-click-modal="false" :visible.sync="dialogImport" width="720px">
			<el-form :model="importUserForm" :rules="importUserRules" ref="importUserValidate" :inline="true">
				<el-form-item label="组织" prop="dept_id" label-width="110px">
					<el-select v-model="importUserForm.dept_id" placeholder="请选择所在组织" style="width:207px;">
						<el-option v-for="item in depts" :key="item.id" :label="item.title" :value="item.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-upload style="text-align:center" ref="upload" action=" " :limit="1" :on-change="fileChange" :before-remove="fileRemove" accept=".xls, .xlsx" :auto-upload="false">
						<el-button type="warning" size="small" @click.stop='downLoadFile' class='uploadBtns'>下载模板</el-button>
						<el-button type="primary" size="small" slot="trigger" class='uploadBtns'>选取文件</el-button>
					</el-upload>
				</el-form-item>
			</el-form>
			<div class="uploadTips">
				<p>请下载模板，并严格按照模板格式整理数据后上传</p>
				<p>只能上传xls/xlsx格式文件</p>
				<p class="red">*注意：请勿重复导入相同数据</p>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="resetImport">取 消</el-button>
				<el-button size="small" type="success" @click="submitUpload">导入用户</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { getUsers, getUser, addUser, updateUser, updateUserPassword, updateUserState, deleteUser, importExcel } from '@/api/sysUser.js'
	import { roleList, getRole } from '@/api/sysRole.js'
	import { deptList } from '@/api/sysDept.js'
	import { majorList } from '@/api/major.js'
	export default {
		name: 'User',
		data() {
			var validatorphone = (rule, value, callback) => {
				let reg = /^1[3456789]\d{9}$/;
				if(!reg.test(value)) {
					callback(new Error('请输入正确的手机号码'))
				} else {
					callback()
				}
			};
			var validatePass1 = (rule, value, callback) => {
				if(this.addForm.passwordcheck) {
					if(value !== this.addForm.passwordcheck) {
						callback(new Error('两次输入密码不一致!'));
					} else {
						callback();
					}
				}
			};
			var validatePass2 = (rule, value, callback) => {
				if(this.addForm.password) {
					if(value !== this.addForm.password) {
						callback(new Error('两次输入密码不一致!'));
					} else {
						callback();
					}
				}
			};
			return {
				dialogImport: false,
				users: [],
				roles: [],
				depts: [],
				majors: [],
				current: 1,
				limit: 10,
				total: 0,
				name: '',
				deptId: null,
				addUserDialog: false,
				editUserDialog: false,
				multipleSelect: [],
				dataloading: false,
				props: {
					checkStrictly: true,
					value: 'id',
					label: 'text',
				},
				options: [{
					value: 0,
					label: '男'
				}, {
					value: 1,
					label: '女'
				}],
				// 导入
				importUserForm: {
					dept_id: '',
					excelFile: '',
					roleId: '',
				},
				importUserRules: {
					dept_id: [{
						required: true,
						message: '请选择组织'
					}],
					roleId: [{
						required: true,
						message: '请选择角色'
					}]
				},
				addForm: {
					username: '',
					name: '',
					mobile: '',
					sex: '',
					deptId: '',
					password: '',
					passwordcheck: '',
					userRoles: [],
					userRoleList: [],
				},
				editForm: {
					userId: '',
					username: '',
					name: '',
					mobile: '',
					sex: '',
					deptId: '',
					userRoles: [],
					userRoleList: [],
				},
				rules: {
					username: [{
						required: true,
						message: '请输入用户名'
					}],
					name: [{
						required: true,
						message: '请输入姓名'
					}],
					sex: [{
						required: true,
						message: '请选择性别'
					}],
					deptId: [{
						required: true,
						message: '请选择所在组织'
					}],
					password: [{
							required: true,
							message: '请输入密码'
						},
						{
							validator: validatePass1,
							trigger: 'blur'
						}
					],
					passwordcheck: [{
							required: true,
							message: '请确认密码'
						},
						{
							validator: validatePass2,
							trigger: 'blur'
						}
					],
					userRoleList: [{
						required: true,
						message: '请选择角色权限'
					}],
				},

			}
		},
		created() {
			this.getDeptList();
			this.getRoleList();
			this.getMajorList();
			this.getUserList();
		},
		methods: {
			getUserList() {
				var data = {
					current: this.current,
					limit: this.limit,
					name: this.name ? this.name : null,
					deptId: this.deptId ? this.deptId : null,
				}
				getUsers(data).then(async res => {
					this.users = res.data.records;
					this.total = res.data.total;

				});
			},
			getRoleList() {
				roleList({}).then(async res => {
					this.roles = res.data;
				});
			},
			getDeptList() {
				deptList({}).then(async res => {
					this.depts = res.children
				})
			},
			getMajorList() {
				majorList({}).then(async res => {
					this.majors = res.children
				})
			},

			search() {
				this.current = 1;
				this.getUserList()
			},
			currentChange(page) {
				this.current = page;
				this.getUserList()
			},
			//导入用户
			downLoadFile() {
				var url = 'https://zfatt.oss-cn-beijing.aliyuncs.com/vrOrg/template/studentTemplate.xls';
				var downButton = document.createElement('a');
				downButton.href = url;
				downButton.download = '导入用户模板.zip';
				downButton.click();
				window.URL.revokeObjectURL(url);
			},
			fileChange(file) {
				this.importUserForm.excelFile = file.raw;
			},
			fileRemove(file) {
				this.importUserForm.excelFile = "";
			},
			resetImport() {
				this.dialogImport = false;
				this.$refs.upload.clearFiles();
				this.importUserForm.excelFile = "";
				this.$refs.importUserValidate.clearValidate();
				this.$refs.importUserValidate.resetFields();
			},
			submitUpload() {
				this.$refs.importUserValidate.validate(valid => {
					if(valid) {
						if(this.importUserForm.excelFile === "") {
							this.$message({
								message: "文件不能为空",
								type: "error"
							});
							return;
						} else {
							const loading = this.$loading({
								lock: true,
								text: "正在导入请稍等···",
								spinner: "el-icon-loading",
								background: "rgba(0, 0, 0, 0.7)"
							});
							var formData = new FormData();
							formData.append("deptId", this.importUserForm.dept_id);
							formData.append("file", this.importUserForm.excelFile);
							formData.append("roleId", this.importUserForm.roleId)
							importExcel(formData).then(async res => {
								this.$message({
									message: "导入成功!",
									type: "success"
								});
								loading.close();
								this.dialogImport = false;
								this.importUserForm.excelFile = "";
								this.$refs.upload.clearFiles();
								this.$refs.importUserValidate.clearValidate();
								this.$refs.importUserValidate.resetFields();
								this.getUserList();
							});
						}
					}
				});
			},
			//导出用户
			exportUser() {
				import("@/vendor/Export2Excel").then(excel => {
					const tHeader = ["用户名", "姓名", "组织"];
					const filterVal = ["username", "name", "deptName"];
					const list = this.users;
					for(let i = 0; i < list.length; i++) {
						const data = list[i]
						if(data.sex == 0) {
							data.sex = '男'
						} else {
							data.sex = '女'
						}
					}
					const data = this.formatJson(filterVal, list);
					excel.export_json_to_excel({
						header: tHeader,
						data,
						filename: this.filename,
						autoWidth: this.autoWidth,
						bookType: this.bookType
					});
				})
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]));
			},
			addRoleChange() {
				var userRoles = this.addForm.userRoles;
				var roles = this.roles;
				this.addForm.userRoleList = [];
				if(userRoles.length > 0) {
					var userRoleList = [];
					userRoles.map(item => {
						var userRole = {
							roleId: item
						}
						userRoleList.push(userRole);
					})
					this.addForm.userRoleList = userRoleList;
				}
			},
			addUser() {
				this.dataloading = true;
				setTimeout(_ => {
					this.dataloading = false;
				}, 1000)
				this.$refs.addForm.validate((valid) => {
					if(valid) {
						addUser({
							username: this.addForm.username,
							name: this.addForm.name,
							sex: this.addForm.sex,
							deptId: this.addForm.deptId,
							mobile: this.addForm.mobile,
							password: this.addForm.password,
							userRoleList: this.addForm.userRoleList,
						}).then(async res => {
							if(res.code == "OK") {
								this.$message({
									message: '添加成功',
									type: 'success'
								});
								this.getUserList();
								this.resetAdd();
							} else {
								this.$message({
									message: res.msg,
									type: 'error'
								});
							}
						});
					}
				})
			},
			resetAdd() {
				this.addUserDialog = false;
				this.addForm.userRoles = [];
				this.$refs.addForm.resetFields();
				this.$refs.addForm.clearValidate();
			},
			openEdit(item) {
				this.editUserDialog = true;
				this.editForm.userId = item.userId;
				this.editForm.username = item.username;
				this.editForm.name = item.name;
				this.editForm.sex = item.sex;
				this.editForm.deptId = item.deptId;
				this.editForm.mobile = item.mobile;
				var roles = this.roles;
				getUser({
					userId: item.userId
				}).then(res => {
					this.editForm.userRoleList = res.data.userRoleList;
					if(res.data.userRoleList && res.data.userRoleList.length > 0) {
						var userRoles = [];
						res.data.userRoleList.map(it => {
							userRoles.push(it.roleId);
						})
						this.editForm.userRoles = userRoles;
					}
				})
			},
			editRoleChange() {
				var userRoles = this.editForm.userRoles
				this.editForm.userRoleList = [];
				var roles = this.roles;
				if(userRoles.length > 0) {
					var userRoleList = [];
					userRoles.map(item => {
						var userRole = {
							roleId: item
						}
						userRoleList.push(userRole);
					})
					this.editForm.userRoleList = userRoleList;
				}
			},
			editUser() {
				this.$refs.editForm.validate((valid) => {
					if(valid) {
						updateUser({
							userId: this.editForm.userId,
							username: this.editForm.username,
							name: this.editForm.name,
							sex: this.editForm.sex,
							deptId: this.editForm.deptId,
							mobile: this.editForm.mobile,
							userRoleList: this.editForm.userRoleList,
						}).then(async res => {
							if(res.code == 'OK') {
								this.$message({
									message: '编辑成功',
									type: 'success'
								})
								this.getUserList();
								this.resetEdit();
							} else {
								this.$message({
									message: res.msg,
									type: 'error'
								})
							}
						})
					}
				})
			},
			resetEdit() {
				this.editUserDialog = false;
				this.editForm.userRoles = [];
				this.$refs.editForm.resetFields();
				this.$refs.editForm.clearValidate()
			},
			selectionChange(val) {
				this.multipleSelect = val;
			},
			removeUsers() {
				var multipleSelect = this.multipleSelect;
				if(multipleSelect && multipleSelect.length > 0) {
					var ids = []
					multipleSelect.map(item => {
						ids.push(item.userId)
					})
					ids = ids.join(',')
					this.$confirm('是否删除这些用户?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						deleteUser({
							ids: ids
						}).then(async res => {
							if(res.code == 'OK') {
								this.$message({
									message: '删除成功',
									type: 'success',
								});
							} else {
								this.$message({
									message: res.msg,
									type: 'error',
								});
							}
							this.getUserList();
						})
					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消删除'
						});
					});
				} else {
					this.$message({
						type: 'info',
						message: '请先选择要删除的用户'
					});
				}
			},
			openDelete(userId) {
				this.$confirm('是否删除该用户?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					deleteUser({
						ids: userId
					}).then(async res => {
						if(res.code == 'OK') {
							this.$message({
								message: '删除成功',
								type: 'success'
							})
							this.getUserList();
						} else {
							this.$message({
								message: res.msg,
								type: 'error'
							})
						}
					})
				}).catch(() => {
					this.$message({
						message: '已取消删除',
						type: 'info',
					});
				});
			},
			setPassword(userId) {
				this.$confirm('是否重置密码?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					updateUserPassword({
						userId: userId,
						password: '123',
					}).then(async res => {
						if(res.code == 'OK') {
							this.$message({
								message: res.msg,
								type: 'success'
							})
						} else {
							this.$message({
								message: res.msg,
								type: 'error'
							})
						}
					})
				}).catch(() => {
					this.$message({
						message: '已取消重置',
						type: 'info',
					});
				});

			},

		}
	}
</script>